import React, { useLayoutEffect, useMemo, useRef, useState } from "react";
import { Select } from "antd";
import { useFormField } from "../../context/form-context";
import { useForm } from "../../context/metadata-context";
import get from "lodash/get";
import set from "lodash/set";
import "./index.css";
import useComponentWidth from "../../lifecycle/useComponentWidth";
import { getIeHack, isIE } from "../../utils";
import eventBus from "../../eventBus";

let defaultConfig = {
  //这一批属性来源 tplData.form.data_control （步骤权限）
  // "code": "a16",
  // "name": "下拉固定值",
  // "type": "dropdown",
  // "is_show": true,
  // "is_editable": true,
  // "is_required": false,

  //这一批属性来源 tplData.form.form_meta_data （表单设计器）
  // "isUsed": false,
  // "designProps": {
  //     "code": "a16",
  //     "name": "下拉固定值",
  //     "ui": "wfd_dropdown",
  //     "title": "下拉固定值",
  //     "layout": "control_layout_leftRight",
  //     "defaultValue": "",
  //     "groupTitle": "",
  //     "byTableGroupTitle": false,
  //     "text": "请选择下拉固定值",
  //     "tipstext": "",
  //     "type": "dropdown",
  //     "title_w": 85
  // },

  //这一批属性来源 tplData.form.data_define （业务对象）
  // "show_type_name": "",
  // "show_type": "",
  // "isHide": false,
  // "default_value": "",
  // "is_sys": 0,
  // "props": {
  //     "source_type": "fixd_value",
  //     "configs": [
  //         [
  //             "0",
  //             "固定值1",
  //             "实际值1",
  //             "说明1"
  //         ]
  //     ]
  // },
  // "type_name": "下拉选择",
  
  //来源 tplData.form.defaultValueConf
  // "default": null
}

export default function ({
  field,
  label,
  rules,
  filter,
  onChange,
  displayComponent,
  options = [],
  required,
  loadDataOnMounted = true,
  showLabel = false,
  readOnly = false,
  isSubTableField,
  rangePath,
  sourcePath,
  cell,
  rowIndex,
  groupCode,
  ...others
}) {
  // const loadData = useRef(loadDataOnMounted);
  const { data: tplData } = useForm().root;
  const { input, property, validation, readonly, className, isDisplay } = useFormField({
    field,
    rules,
    onChange,
    triggerBlurAsChange: true,
  });

  const wrapperRef = useRef();
  let width = useComponentWidth(wrapperRef);
  
  if (Array.isArray(input.value)) {
    let value = null;
    if(Array.isArray(input.value[0])){
      let defaultValueArray = input.value.find((v) => v[0] == 1) || [];
      //checkbox从索引1里面取
      if (defaultValueArray[2] !== undefined) {
        value = defaultValueArray[2];
      }
    }else if(input.value[0] === undefined){
      //联动后，后端返回的联动结果可能是个[], input.value[0]是没有值的，这种情况把value重置为null，然后再触发一次change事件
      value = null;
      input.value = [];
    }
    //更新选项
    set(tplData, rangePath, input.value);
    set(tplData, sourcePath, input.value);

    //更新说明文字
    let remarkPath = "refreshRemarkTip.form.data_range.main." + cell.code;
    if(isSubTableField) {
      remarkPath = "refreshRemarkTip.form.data_range.children." + groupCode + "." + cell.code;
    }
    eventBus.publishAsync(remarkPath);

    input.onChange(value);
    return null;
  }
  let optionData = get(tplData, rangePath); //查找固定值配置
  if (!optionData) {
    optionData = get(tplData, sourcePath); //查找关键字链接配置
  }
  if (!optionData) {
    optionData = [];
  }

  // if(Array.isArray(input.value)){
  //   if(!optionData[2]){

  //   }
  // }
  if (isDisplay) {
    //返回下拉的只读文本
    function getDisplayField(value) {
      var txt = "";
      if (optionData) {
        optionData.find(function (item) {
          if (value + "" == item[2] + "") {
            //item的第2个是实际值
            txt = item[1]; //item的第1个是显示值
          }
          return value + "" == item[2] + "";
        });
      }
      return txt;
    }
    return input.value === undefined ? null : getDisplayField(input.value);
  }

  let component = <Select
        style={{ width: "100%" }}
        className={className}
        {...input}
        placeholder={cell?.designProps?.text ? cell?.designProps?.text : "请选择"}
        disabled={property.disabled}
        {...others}
        {...readonly}
        {...getIeHack()}
      >
        {optionData.map((option, index) => (
          <Select.Option key={option[2] + index} value={option[2]}>
            {option[1]}
          </Select.Option>
        ))}
        
      </Select>;

  return (
    <div ref={wrapperRef} style={{ maxWidth: width }}>
      {component}
    </div>
  );
}
